from PyQt4 import QtCore, QtGui
import threading
import time
import sys
sys.path.append("..")
from Base import TaskModel, Singleton


class _Watcher(QtGui.QWidget, TaskModel.ObserverModel):
    def __init__(self, observer_list):
        super(QtGui.QWidget, self).__init__()
        TaskModel.ObserverModel.__init__(self, observer_list)
        self.__WatchClipboard()
        self.bWatch = True

    def Notify(self, observer, task, result):
        observer.OnClipboardChange(result)

    def __WatchClipboard(self):
        self.clipboard = QtGui.QApplication.clipboard()
        self.clipboard.dataChanged.connect(self.__OnClipboardChange, QtCore.Qt.QueuedConnection)
        
    @QtCore.pyqtSlot()
    def __OnClipboardChange(self):
        if not self.bWatch:
            return
        self.NotifyObservers(None, self.clipboard.text())
    
    def StartWatch(self):
        self.bWatch = True
        
    def StopWatch(self):
        self.bWatch = False
    
        

class QtApp(threading.Thread):
    def __init__(self, observer_list):
        threading.Thread.__init__(self)
        self.watcher = None
        self.observer_list = observer_list
        self.start()
        
    def run(self):
        app = QtGui.QApplication(sys.argv)
        self.watcher = _Watcher(self.observer_list)
        app.exec_()

class ClipboardObserver(TaskModel.Observer):        
    def OnClipboardChange(self, data):
        print data


class ClipboardWatcher(TaskModel.ObserverModel, Singleton.Singleton):
    '''When the Clipboard's data Changed, It will Notify the Observers'''
    def __init__(self):
        TaskModel.ObserverModel.__init__(self)
        self.app = QtApp(self.GetObserverList())
 
        



if __name__ == '__main__':
    ob = ClipboardObserver()
    watcher = ClipboardWatcher.Instance()
    watcher.AddObserver(ob)
    
    

    